Get Maximum in each Group

您所在的位置:网站首页 dataframe decimal groupby Get Maximum in each Group

Get Maximum in each Group

2024-07-13 09:44| 来源: 网络整理| 查看: 265

You can use Pandas groupby to group the underlying data on one or more columns and estimate useful statistics like count, mean, median, min, max etc. In this tutorial, we will look at how to get the maximum value for each group in pandas groupby with the help of some examples.

Maximum value in each group of pandas dataframe Pandas Groupby Maximum

To get the maximum value of each group, you can directly apply the pandas max() function to the selected column(s) from the result of pandas groupby. The following is a step-by-step guide of what you need to do.

Group the dataframe on the column(s) you want.Select the field(s) for which you want to estimate the maximum.Apply the pandas max() function directly or pass ‘max’ to the agg() function.

The following is the syntax –

# groupby columns on Col1 and estimate the maximum value of column Col2 for each group df.groupby([Col1])[Col2].max() # alternatively, you can pass 'max' to the agg() function df.groupby([Col1])[Col2].agg('max') Examples

Let’s look at some examples of using the above syntax to get the max value for each group in pandas. First, we will create a sample dataframe that we will be using throughout this tutorial.

import pandas as pd # create a dataframe of car models by two companies df = pd.DataFrame({ 'Company': ['A', 'A', 'A', 'B', 'B', 'B', 'B'], 'Model': ['A1', 'A2', 'A3', 'B1', 'B2', 'B3', 'B4'], 'Year': [2019, 2020, 2021, 2018, 2019, 2020, 2021], 'Transmission': ['Manual', 'Automatic', 'Automatic', 'Manual', 'Automatic', 'Automatic', 'Manual'], 'EngineSize': [1.4, 2.0, 1.4, 1.5, 2.0, 1.5, 1.5], 'MPG': [55.4, 67.3, 58.9, 52.3, 64.2, 68.9, 83.1] }) # display the dataframe df

Output:

Dataframe of car models and their specifications from two car companies

Now we have a dataframe containing the specifications of the car models by two different companies. The “EngineSize” column is the size of the engine in litres and the “MPG” column is the mileage of the car in miles-per-gallon.

1. Groupby Maximum of a single column

Let’s get the maximum value of mileage “MPG” for each “Company” in the dataframe df. To do this, group the dataframe on the column “Company”, select the “MPG” column, and then apply the max() function.

# max MPG for each Company df.groupby('Company')['MPG'].max()

Output:

📚 Data Science Programs By Skill Level

Introductory ⭐

Harvard University Data Science: Learn R Basics for Data Science Standford University Data Science: Introduction to Machine Learning UC Davis Data Science: Learn SQL Basics for Data Science IBM Data Science: Professional Certificate in Data Science IBM Data Analysis: Professional Certificate in Data Analytics Google Data Analysis: Professional Certificate in Data Analytics IBM Data Science: Professional Certificate in Python Data Science IBM Data Engineering Fundamentals: Python Basics for Data Science

Intermediate ⭐⭐⭐

Harvard University Learning Python for Data Science: Introduction to Data Science with Python Harvard University Computer Science Courses: Using Python for Research IBM Python Data Science: Visualizing Data with Python DeepLearning.AI Data Science and Machine Learning: Deep Learning Specialization

Advanced ⭐⭐⭐⭐⭐

UC San Diego Data Science: Python for Data Science UC San Diego Data Science: Probability and Statistics in Data Science using Python Google Data Analysis: Professional Certificate in Advanced Data Analytics MIT Statistics and Data Science: Machine Learning with Python - from Linear Models to Deep Learning MIT Statistics and Data Science: MicroMasters® Program in Statistics and Data Science

🔎 Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

Company A 67.3 B 83.1 Name: MPG, dtype: float64

You can see that maximum mileage “MPG” for company “B” is higher than that of company “A”.

Alternatively, you can also use the pandas agg() function on the resulting groups.

# max MPG for each Company df.groupby('Company')['MPG'].agg('max')

Output:

Company A 67.3 B 83.1 Name: MPG, dtype: float64

We get the same result as above.

You can also group the data on multiple columns (to get more granular groups) and then compute the max for each group. For example, let’s group the data on “Company” and “Transmission” and get the maximum “MPG” for each group.

# max MPG for each Company at a transmission level df.groupby(['Company', 'Transmission'])['MPG'].max()

Output:

Company Transmission A Automatic 67.3 Manual 55.4 B Automatic 68.9 Manual 83.1 Name: MPG, dtype: float64 2. Groupby Maximum of multiple columns

You can also get the maximum value of different columns for each group resulting from pandas groupby. For example, let’s get the maximum of mileage “MPG” and “EngineSize” for each “Company” in the dataframe df.

# max MPG and EngineSize for each Company df.groupby('Company')[['MPG', 'EngineSize']].max()

Output:

Maximum value for "MPG" and "EngineSize" columns for each group represented by the company.

Here we selected the columns that we wanted to compute the maximum on from the resulting groupby object and then applied the max() function. We already know that the maximum “MPG” is higher for company “B” but the maximum “EngineSize” is equal for both the companies.

Let’s now do the same thing using the pandas agg() function.

# max MPG and EngineSize for each Company df.groupby('Company')[['MPG', 'EngineSize']].agg('max')

Output:

Maximum value for "MPG" and "EngineSize" columns for each group represented by the company.

We get the same result as above.

With this, we come to the end of this tutorial. The code examples and results presented in this tutorial have been implemented in a Jupyter Notebook with a python (version 3.8.3) kernel having pandas version 1.0.5

Subscribe to our newsletter for more informative guides and tutorials. We do not spam and you can opt out any time.

Author Piyush Raj Piyush Raj

Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

View all posts



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3